<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
        </div>
      </template>

      <el-form
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="100px"
        class="profile-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileForm.username" disabled :maxlength="50" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="profileForm.nickname" :maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="profileForm.phone" :maxlength="11" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" :maxlength="100" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-input v-model="profileForm.createdAt" disabled :maxlength="50" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleUpdateProfile">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>

      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
        class="password-form"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password :maxlength="50" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password :maxlength="50" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password :maxlength="50" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
          <el-button @click="resetPasswordForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'
import { preventDuplicateSubmit } from '@/utils'

const userStore = useUserStore()

const profileFormRef = ref()
const passwordFormRef = ref()

const profileForm = reactive({
  username: '',
  nickname: '',
  phone: '',
  email: '',
  createdAt: ''
})

const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 初始化表单数据
const initFormData = () => {
  if (userStore.userInfo) {
    profileForm.username = userStore.userInfo.username
    profileForm.nickname = userStore.userInfo.name
    profileForm.phone = userStore.userInfo.phone || ''
    profileForm.email = userStore.userInfo.email || ''
    profileForm.createdAt = userStore.userInfo.createdAt || ''
  }
}

// 更新个人资料
const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return

  await profileFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await preventDuplicateSubmit('update_profile', async () => {
          try {
            const success = await userStore.updateProfile({
              nickname: profileForm.nickname,
              phone: profileForm.phone,
              email: profileForm.email
            })

            if (success) {
              ElMessage.success('个人资料更新成功')
            }
          } catch (error: any) {
            ElMessage.error('个人资料更新失败')
            throw error // 重新抛出错误以确保防重复提交正确处理
          }
        })
      } catch (error: any) {
        // 防重复提交保护捕获的错误
        if (error.message === '请勿重复提交') {
          ElMessage.warning('请勿重复提交')
        }
      }
    }
  })
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await preventDuplicateSubmit('change_password', async () => {
          try {
            const success = await userStore.changePassword(
              passwordForm.oldPassword,
              passwordForm.newPassword
            )

            if (success) {
              ElMessage.success('密码修改成功')
              resetPasswordForm()
            }
          } catch (error: any) {
            ElMessage.error('密码修改失败')
            throw error // 重新抛出错误以确保防重复提交正确处理
          }
        })
      } catch (error: any) {
        // 防重复提交保护捕获的错误
        if (error.message === '请勿重复提交') {
          ElMessage.warning('请勿重复提交')
        }
      }
    }
  })
}

// 重置个人资料表单
const resetForm = () => {
  initFormData()
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

onMounted(() => {
  initFormData()
})
</script>

<style scoped lang="scss">
.profile-container {
  .profile-card {
    margin-bottom: 20px;

    .card-header {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .password-card {
    .card-header {
      font-size: 18px;
      font-weight: 600;
    }
  }
}
</style>
